package util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import domain.File;
import domain.Profile;
import domain.User;

public class CSVReader {

	/**
	 * Imports users' profiles from a CSV file. Parameters in the .csv file
	 * should be in the format: document number, first name, last name, main
	 * email, student code, birthdate, phones, personal emails (separated by
	 * "/") The first line will not be taken into account. Birthdate needs to be
	 * in the format "dd/MM/yyyy"
	 * 
	 * @param filename
	 *            Name of the file to import
	 * @return List of profiles with reference to its corresponding user.
	 * @throws ParseException 
	 */
	public static List<User> importUsers(File file) throws ParseException {
		List<User> users = new ArrayList<User>();
		String fileString = new String(file.getData());
		String[] lines = fileString.split("\n");
		int i = 0;
		for (String strLine: lines) {
			if (i++ != 0 && !strLine.trim().isEmpty() && !strLine.contains(",,,,,,")) {
				try {
					User user = parseAndCreateUser(strLine);
					if (user != null) {
						users.add(user);
					}
				} catch (Exception e) {
					throw new ParseException("Hubo un error al leer la línea " + i + " del archivo. Por favor corregir el formato CSV.", 0);
				}
			}
		}
		return users;
	}

	private static User parseAndCreateUser(String strLine) throws ParseException {
		String[] variables = strLine.split(",", -1);
		User user = new User(variables[0], variables[1], variables[2], variables[3]);
		SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
		Date birthdate = dtf.parse(variables[5]);
		Profile p = new Profile(user, variables[4], birthdate, variables[6], variables[7]);
		user.setProfile(p);
		return user;
	}

}
